package com.xinqi.modules.mq.rongyun.mq.consumer;

import com.alibaba.fastjson.JSONObject;
import com.xinqi.common.base.enums.YesNoNumberEnum;
import com.xinqi.common.core.enums.RocketMqEnum;
import com.xinqi.common.core.enums.RocketMqRongyunEnum;
import com.xinqi.common.rocketmq.dto.ChatFriendMessageBody;
import com.xinqi.common.rocketmq.dto.ChatGroupMessageBody;
import com.xinqi.common.rocketmq.dto.RocketMqBean;
import com.xinqi.common.rocketmq.util.ByteUtils;
import com.xinqi.modules.chat.enums.friend.FriendStatusEnum;
import com.xinqi.modules.mq.rongyun.third.service.RongyunService;
import io.rong.util.CodeUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.apis.*;
import org.apache.rocketmq.client.apis.consumer.FilterExpression;
import org.apache.rocketmq.client.apis.consumer.FilterExpressionType;
import org.apache.rocketmq.client.apis.consumer.SimpleConsumer;
import org.apache.rocketmq.client.apis.consumer.SimpleConsumerBuilder;
import org.apache.rocketmq.client.apis.message.MessageView;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * @version V1.0
 * @Title:融云--操作类MQ消息监听
 * @Description:
 * @Copyright 星齐科技（云南）有限公司 - Powered By 技术部
 * @author: yyzhen
 * @date: 2023/7/25 11:10
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class RongyunOperationConsumer {

    private final RongyunService rongyunService;

    @Async
    public void pushOperationConsumerMsg(RocketMqBean rocketMqBean, RocketMqEnum mqEnum) throws ClientException {
        log.info("融云--操作类MQ消息监听启动 => {}", mqEnum);
        ClientServiceProvider provider = ClientServiceProvider.loadService();

        SessionCredentialsProvider sessionCredentialsProvider =
            new StaticSessionCredentialsProvider(rocketMqBean.getUsername(), rocketMqBean.getPassword());

        ClientConfiguration clientConfiguration = ClientConfiguration.newBuilder()
            .setEndpoints(rocketMqBean.getEndpoints())
            .setCredentialProvider(sessionCredentialsProvider)
            .build();
        Duration awaitDuration = Duration.ofSeconds(30);
        FilterExpression filterExpression = new FilterExpression(mqEnum.getCode(), FilterExpressionType.TAG);
        SimpleConsumerBuilder simpleConsumerBuilder = provider.newSimpleConsumerBuilder()
            .setClientConfiguration(clientConfiguration)
            .setConsumerGroup(mqEnum.getCode())
            .setAwaitDuration(awaitDuration)
            .setSubscriptionExpressions(Collections.singletonMap(rocketMqBean.getTopic(), filterExpression));
        try {
            startConsumer(simpleConsumerBuilder);
        } catch (Exception e) {
            startConsumer(simpleConsumerBuilder);
        }
    }

    /**
     * 启动消费服务
     * @author dzy
     */
    private void startConsumer(SimpleConsumerBuilder simpleConsumerBuilder) throws ClientException {
        SimpleConsumer consumer = simpleConsumerBuilder.build();
        // Max message num for each long polling.
        int maxMessageNum = 20;
        // Set message invisible duration after it is received.
        Duration invisibleDuration = Duration.ofSeconds(10);
        do {
            List<MessageView> messages = consumer.receive(maxMessageNum, invisibleDuration);
            log.info("RONGYUN_OPERATION => 本次获取 {} 条message", messages.size());
            for (MessageView messageView : messages) {
                try {
                    //MQ消息校验
                    String message = ByteUtils.byteBufferToStr(messageView.getBody());
                    if (StringUtils.isEmpty(message)) {
                        consumer.ack(messageView);
                    }
                    JSONObject json = JSONObject.parseObject(message);
                    if (Objects.isNull(json)) {
                        consumer.ack(messageView);
                    }
                    boolean flag = processingMessages(json);
                    if (flag) {
                        consumer.ack(messageView);
                    }
                } catch (Throwable t) {
                    log.error("融云 -- 操作类MQ消费消息异常 => {}", messageView);
                }
            }
        } while (true);
    }

    /**
     * 根据类型区分业务处理
     *
     * @param json
     * @return
     */
    public boolean processingMessages(JSONObject json) {
        boolean flag = Boolean.TRUE;
        //业务类型区分
        String type = json.getString("type");
        if (StringUtils.isEmpty(type)) {
            return flag;
        }
        //业务处理
        if (Objects.equals(RocketMqRongyunEnum.RONGYUN_USER_DEACTIVATE.getCode(), type)) {
            //融云--账号注销
            flag = deactivate(JSONObject.parseObject(json.toJSONString(), ChatGroupMessageBody.class));
        } else if (Objects.equals(RocketMqRongyunEnum.RONGYUN_GAG_ADD.getCode(), type)) {
            //融云--禁言指定群成员
            flag = gagAdd(JSONObject.parseObject(json.toJSONString(), ChatGroupMessageBody.class));
        } else if (Objects.equals(RocketMqRongyunEnum.RONGYUN_GAG_REMOVE.getCode(), type)) {
            //融云--取消指定群成员禁言
            flag = gagRemove(JSONObject.parseObject(json.toJSONString(), ChatGroupMessageBody.class));
        } else if (Objects.equals(RocketMqRongyunEnum.RONGYUN_GROUP_CREATE.getCode(), type)) {
            //融云--创建群聊
            flag = groupCreate(JSONObject.parseObject(json.toJSONString(), ChatGroupMessageBody.class));
        } else if (Objects.equals(RocketMqRongyunEnum.RONGYUN_GROUP_JOIN.getCode(), type)) {
            //融云--加入群聊
            flag = groupJoin(JSONObject.parseObject(json.toJSONString(), ChatGroupMessageBody.class));
        } else if (Objects.equals(RocketMqRongyunEnum.RONGYUN_GROUP_QUIT.getCode(), type)) {
            //融云--退出群聊
            flag = groupQuit(JSONObject.parseObject(json.toJSONString(), ChatGroupMessageBody.class));
        } else if (Objects.equals(RocketMqRongyunEnum.RONGYUN_GROUP_UPDATE.getCode(), type)) {
            //融云--更新群组名称
            flag = groupUpdate(JSONObject.parseObject(json.toJSONString(), ChatGroupMessageBody.class));
        } else if (Objects.equals(RocketMqRongyunEnum.RONGYUN_GROUP_DISMISS.getCode(), type)) {
            //融云--解散群聊
            flag = groupDismiss(JSONObject.parseObject(json.toJSONString(), ChatGroupMessageBody.class));
        } else if (Objects.equals(RocketMqRongyunEnum.RONGYUN_PRIVATE_BLACK_REMOVE.getCode(), type)) {
            //融云--私聊--移除黑名单
            flag = privateBlackRemove(JSONObject.parseObject(json.toJSONString(), ChatFriendMessageBody.class));
        } else if (Objects.equals(RocketMqRongyunEnum.RONGYUN_PRIVATE_CONVERSATION_UNMUTE.getCode(), type)) {
            //融云--私聊--取消免打扰
            flag = privateConversationUnMute(JSONObject.parseObject(json.toJSONString(), ChatFriendMessageBody.class));
        } else if (Objects.equals(RocketMqRongyunEnum.RONGYUN_PRIVATE_CONVERSATION_UN_TOP.getCode(), type)) {
            //融云--私聊--取消置顶
            flag = privateConversationUnTop(JSONObject.parseObject(json.toJSONString(), ChatFriendMessageBody.class));
        }

        return flag;
    }


    /**
     * 融云--账号注销
     *
     * @param body
     * @return
     */
    private boolean deactivate(ChatGroupMessageBody body) {
        if (Objects.isNull(body)) {
            return Boolean.TRUE;
        }
        if (Objects.isNull(body.getUserId())) {
            return Boolean.TRUE;
        }
        return rongyunService.deactivate(body.getUserId().toString());
    }

    /**
     * 融云--禁言指定群成员
     *
     * @param body
     * @return
     */
    private boolean gagAdd(ChatGroupMessageBody body) {
        if (Objects.isNull(body)) {
            return Boolean.TRUE;
        }
        if (StringUtils.isEmpty(body.getGroupId())) {
            return Boolean.TRUE;
        }
        String[] userIds = body.getUserIds();
        if (Objects.isNull(userIds) || userIds.length == 0) {
            return Boolean.TRUE;
        }
        return rongyunService.groupTaboo(body.getGroupId(), userIds);
    }

    /**
     * 融云--取消指定群成员禁言
     *
     * @param body
     * @return
     */
    private boolean gagRemove(ChatGroupMessageBody body) {
        if (Objects.isNull(body)) {
            return Boolean.TRUE;
        }
        if (StringUtils.isEmpty(body.getGroupId())) {
            return Boolean.TRUE;
        }
        String[] userIds = body.getUserIds();
        if (Objects.isNull(userIds) || userIds.length == 0) {
            return Boolean.TRUE;
        }
        return rongyunService.groupTabooClose(body.getGroupId(), userIds);
    }

    /**
     * 融云--创建群聊
     *
     * @param body
     * @return
     */
    private boolean groupCreate(ChatGroupMessageBody body) {
        if (Objects.isNull(body)) {
            return Boolean.TRUE;
        }
        if (Objects.isNull(body.getUserId())) {
            return Boolean.TRUE;
        }
        if (StringUtils.isEmpty(body.getGroupId())) {
            return Boolean.TRUE;
        }
        if (StringUtils.isEmpty(body.getGroupName())) {
            body.setGroupName(StringUtils.EMPTY);
        }
        return rongyunService.creatGroup(body.getGroupId(), body.getGroupName(), body.getUserId().toString());
    }

    /**
     * 融云--加入群聊
     *
     * @param body
     * @return
     */
    private boolean groupJoin(ChatGroupMessageBody body) {
        if (Objects.isNull(body)) {
            return Boolean.TRUE;
        }
        if (StringUtils.isEmpty(body.getGroupId())) {
            return Boolean.TRUE;
        }
        if (StringUtils.isEmpty(body.getGroupName())) {
            body.setGroupName(StringUtils.EMPTY);
        }
        String[] userIds = body.getUserIds();
        if (Objects.isNull(userIds) || userIds.length == 0) {
            return Boolean.TRUE;
        }
        return rongyunService.joinGroup(body.getGroupId(), body.getGroupName(), userIds);
    }

    /**
     * 融云--退出群聊
     *
     * @param body
     * @return
     */
    private boolean groupQuit(ChatGroupMessageBody body) {
        if (Objects.isNull(body)) {
            return Boolean.TRUE;
        }
        if (StringUtils.isEmpty(body.getGroupId())) {
            return Boolean.TRUE;
        }
        if (StringUtils.isEmpty(body.getGroupName())) {
            body.setGroupName(StringUtils.EMPTY);
        }
        String[] userIds = body.getUserIds();
        if (Objects.isNull(userIds) || userIds.length == 0) {
            return Boolean.TRUE;
        }
        return rongyunService.quitGroup(body.getGroupId(), body.getGroupName(), userIds);
    }

    /**
     * 融云--更新群组名称
     *
     * @param body
     * @return
     */
    private boolean groupUpdate(ChatGroupMessageBody body) {
        if (Objects.isNull(body)) {
            return Boolean.TRUE;
        }
        if (StringUtils.isEmpty(body.getGroupId())) {
            return Boolean.TRUE;
        }
        if (StringUtils.isEmpty(body.getGroupName())) {
            return Boolean.TRUE;
        }
        return rongyunService.updateGroup(body.getGroupId(), body.getGroupName());
    }

    /**
     * 融云--解散群聊
     *
     * @param body
     * @return
     */
    private boolean groupDismiss(ChatGroupMessageBody body) {
        if (Objects.isNull(body)) {
            return Boolean.TRUE;
        }
        if (Objects.isNull(body.getUserId())) {
            return Boolean.TRUE;
        }
        if (StringUtils.isEmpty(body.getGroupId())) {
            return Boolean.TRUE;
        }
        return rongyunService.dissGroup(body.getGroupId(), body.getUserId().toString());
    }

    /**
     * 融云--私聊--移除黑名单
     *
     * @param body
     * @return
     */
    private boolean privateBlackRemove(ChatFriendMessageBody body) {
        if (Objects.isNull(body)) {
            return Boolean.TRUE;
        }
        if (Objects.isNull(body.getUserId())) {
            return Boolean.TRUE;
        }
        if (Objects.isNull(body.getFriendId())) {
            return Boolean.TRUE;
        }
        return rongyunService.blackManager(body.getUserId().toString(), body.getFriendId().toString(), FriendStatusEnum.ONE.getCode());
    }

    /**
     * 融云--私聊--取消免打扰
     *
     * @param body
     * @return
     */
    private boolean privateConversationUnMute(ChatFriendMessageBody body) {
        if (Objects.isNull(body)) {
            return Boolean.TRUE;
        }
        if (Objects.isNull(body.getUserId())) {
            return Boolean.TRUE;
        }
        if (Objects.isNull(body.getFriendId())) {
            return Boolean.TRUE;
        }
        return rongyunService.conversationDisturb(body.getUserId().toString(), body.getFriendId().toString(), CodeUtil.ConversationType.PRIVATE, YesNoNumberEnum.NO.getCode());
    }


    /**
     * 融云--私聊--取消置顶
     *
     * @param body
     * @return
     */
    private boolean privateConversationUnTop(ChatFriendMessageBody body) {
        if (Objects.isNull(body)) {
            return Boolean.TRUE;
        }
        if (Objects.isNull(body.getUserId())) {
            return Boolean.TRUE;
        }
        if (Objects.isNull(body.getFriendId())) {
            return Boolean.TRUE;
        }
        return rongyunService.conversationTop(body.getUserId().toString(), CodeUtil.ConversationType.PRIVATE.getName(), body.getFriendId().toString(), false);
    }

}
